package com.siren.tank.group.image;

import com.siren.tank.*;
import com.siren.tank.fire.FireStrategy;
import com.siren.tank.fire.SingleFire;
import com.siren.tank.group.BaseTank;

import java.awt.*;
import java.util.Map;
import java.util.Random;

/**
 * @author : wangjichao
 * @description:
 * @date : 2020/7/29 10:33
 */
public class BadTank extends BaseTank {

    private Random random = new Random();

    private static final int SPEED = 3;

    private boolean moving = true;

    private FireStrategy fireStrategy = new SingleFire();

    public BadTank(int x, int y, Dir dir) {
        super(x, y, dir);
        setGroup(Group.BAD);
        GameModel.getInstance().add(this);
    }

    public boolean isMoving() {
        return this.moving;
    }

    public void setMoving(boolean moving) {
        this.moving = moving;
    }

    @Override
    public void control(Map<Integer, Boolean> keyEvents) {

    }

    @Override
    public void draw(Graphics g) {
        randomDir();
        if (!this.isLive()) {
            GameModel.getInstance().remove(this);
            return;
        }
        switch (getDir()) {
            case LEFT:
                g.drawImage(ResourceMgr.tankL, getX(), getY(), null);
                break;
            case RIGHT:
                g.drawImage(ResourceMgr.tankR, getX(), getY(), null);
                break;
            case UP:
                g.drawImage(ResourceMgr.tankU, getX(), getY(), null);
                break;
            case DOWN:
                g.drawImage(ResourceMgr.tankD, getX(), getY(), null);
                break;
        }
        move();
        this.fire(this.fireStrategy);

    }

    private void move() {
        // 记录之前的位置
        setOldX(getX());
        setOldY(getY());

        if (isMoving()) {
            switch (getDir()) {
                case LEFT:
                    setX(getX() - SPEED);
                    break;
                case RIGHT:
                    setX(getX() + SPEED);
                    break;
                case UP:
                    setY(getY() - SPEED);
                    break;
                case DOWN:
                    setY(getY() + SPEED);
                    break;
                default:
                    break;
            }
        }
    }

    public void randomDir() {
        if (random.nextInt(10) < 8) {
            return;
        }
        switch (random.nextInt(4)) {
            case 0:
                setDir(Dir.LEFT);
                break;
            case 1:
                setDir(Dir.RIGHT);
                break;
            case 2:
                setDir(Dir.UP);
                break;
            case 3:
                setDir(Dir.DOWN);
                break;
        }
    }


    public void fire(FireStrategy fireStrategy) {
        if (random.nextInt(10) > 8) {
            fireStrategy.fire(this);
        }
    }
}
